package com.liuzy.movie;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DB {

	Connection conn;

	public DB(String host, int port, String dbname, String uname, String pwd) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+dbname, uname, pwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void close() {
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public int insert(String title, byte[] image, String download) {
		try {
			String sql = "INSERT INTO `video`(`title`, `image`, `download`) VALUES (?,?,?);";
			PreparedStatement stat = conn.prepareStatement(sql);
			stat.setString(1, title);
			stat.setBytes(2, image);
			stat.setString(3, download);
			int count = stat.executeUpdate();
			stat.close();
			return count;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public List<String> select(String keywords) {
		List<String> list = new ArrayList<String>();
		try {
			Statement stat = conn.createStatement();
			String sql = "select download from video where title like '%" + (keywords == null ? "" : keywords) + "%'";
			ResultSet rs = stat.executeQuery(sql);
			while (rs.next()) {
				list.add(rs.getString("download"));
			}
			conn.close();
			stat.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}
